package com.example.deepseekwebsocket.websocket;

import com.example.deepseekwebsocket.service.DeepSeekService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Deque;
import java.util.LinkedList;


/**
 * @Description: WebSocketServer
 * @Author: 菜鸟Lm
 */
@Component
public class WebSocketServer extends TextWebSocketHandler {

    @Autowired
    private DeepSeekService deepSeekService;


    /**
     * 连接建立成功调用
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接建立成功" + session.getId());
    }

    // 用于DeepSeek存储消息历史记录 TODO 非实际场景
    private final Deque<String> messageHistory = new LinkedList<>();

    /**
     * 接收消息调用
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        // 获得客户端传来的消息
        String payload = (String) message.getPayload();
        String systemMessage = null;
        // 判断DeepSeek是否有记录
        if (messageHistory.size() > 0) {
             // 获得DeepSeek最后一条消息
//             systemMessage = deepSeekService.localDeepSeekAip(payload, messageHistory.getLast());
            systemMessage = deepSeekService.officialDeepSeekAip(payload, messageHistory.getLast());
        } else {
//             systemMessage = deepSeekService.localDeepSeekAip(payload, "");
            systemMessage = deepSeekService.officialDeepSeekAip(payload, "");
        }
        messageHistory.add(systemMessage);
        session.sendMessage(new TextMessage(systemMessage));
    }

    /**
     * socket 断开连接时
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

    }


}
